<?php


namespace app\services\goods;



use app\models\goods\GoodsSkuModel;
use app\models\shop\ShopModel;
use app\services\BaseService;
use think\facade\Db;

use app\services\config\ConfigService;
use app\models\goods\GoodsModel;
use app\models\goods\GoodsCartModel;

class GoodsCartService extends BaseService
{

    protected static function initModel()
    {
        return new GoodsCartModel();
    }


    public static function getList($userId)
    {
        try {
            $list = GoodsCartModel::where('user_id', $userId)->select()->toArray();
            $shop_ids = array_column($list,'shop_id');
            $shop_data = (new ShopModel())->where('id','in',$shop_ids)->column('id,shop_name,img','id');

            $config_shop = ConfigService::getConfigValueArray(['shop_name','shop_logo']);
            $shop_data[0] = ['id'=>0,'shop_name' => $config_shop['shop_name'],'img' => $config_shop['shop_logo']];

            $data = [];
            foreach ($list as &$value) {
                $goodsInfo = GoodsModel::where('id', $value['goods_id'])->find();
                $value['shop_id'] = intval($value['shop_id']);
                $value['goods_name'] = $goodsInfo['name'];
                $value['sell_price'] = $goodsInfo['sell_price'];
                $value['market_price'] = $goodsInfo['market_price'];
                $value['goods_image'] = $goodsInfo['image'];
                $value['stock'] = $goodsInfo['stock'];
                $goodsSku = GoodsSkuModel::where('id', $value['goods_sku_id'])->find();
                if($goodsSku){
                    $value['sku_name'] = $goodsSku['name'];
                    $value['sku_sell_price'] = $goodsSku['sell_price'];
                    $value['sku_market_price'] = $goodsSku['market_price'];
                    $value['sku_stock'] = $goodsSku['stock'];
                }else{
                    $value['sku_name'] = '';
                    $value['sku_sell_price'] = "0";
                    $value['sku_market_price'] = "0";
                    $value['sku_stock'] = "0";
                }

                if(isset($data[$value['shop_id']])){
                    $data[$value['shop_id']]['goods'][] = $value;
                }else{
                    $data[$value['shop_id']] = [];
                    $data[$value['shop_id']]['shop'] = $shop_data[$value['shop_id']];
                    $data[$value['shop_id']]['goods'] = [$value];
                }
            }
            return $data;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }


}